<template>
  <common-header page-title="惠农政策宣传" />
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">惠农政策宣传</h1>
      <p class="page-subtitle">及时了解最新农业政策，助力乡村振兴发展</p>
    </div>

    <div class="policy-list">
      <div
          class="policy-card"
          v-for="(policy, index) in policies"
          :key="index"
          @click="$router.push({ name: 'PolicyDetail', params: { id: policy.id } })"
      >
        <div class="policy-content">
          <div class="policy-header">
            <h3 class="policy-title">{{ policy.title }}</h3>
            <span class="policy-tag" :class="{'new-policy': isNewPolicy(policy.publishTime)}">
              {{ getPolicyTag(policy.publishTime) }}
            </span>
          </div>

          <div class="policy-meta">
            <span class="meta-item">
              <i class="el-icon-office-building"></i>
              {{ policy.source || '农业农村部' }}
            </span>
            <span class="meta-item">
              <i class="el-icon-clock"></i>
              {{ formatDate(policy.publishTime) }}
            </span>
            <span class="meta-item">
              <i class="el-icon-view"></i>
              {{ policy.viewCount || 0 }}次浏览
            </span>
          </div>

          <p class="policy-excerpt">{{ truncate(policy.content, 120) }}</p>

          <div v-if="policy.video" class="policy-video">
            <div class="video-thumbnail">
              <img :src="getVideoThumbnail(policy.video)" alt="视频封面">
              <div class="video-play-icon">
                <i class="el-icon-video-play"></i>
              </div>
            </div>
          </div>

          <div class="policy-footer">
            <button
                v-if="policy.attachment"
                @click.stop="handleDownload(policy)"
                class="download-btn"
            >
              <i class="el-icon-download"></i>
              下载附件
            </button>
            <span class="policy-arrow">
              <i class="el-icon-arrow-right"></i>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import request from '@/utils/request'
import CommonHeader from '@/views/user/support/components/CommonHeader.vue'

const policies = ref([])
const pollIntervals = ref({})

// 判断是否为新政策（7天内）
const isNewPolicy = (publishTime) => {
  if (!publishTime) return false
  const publishDate = new Date(publishTime)
  const now = new Date()
  const diffTime = now - publishDate
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays <= 7
}

// 获取政策标签文本
const getPolicyTag = (publishTime) => {
  return isNewPolicy(publishTime) ? '新政策' : '政策'
}

// 生成视频缩略图（模拟）
const getVideoThumbnail = (videoUrl) => {
  // 实际应用中，这里可以调用视频API获取缩略图
  // 这里只是模拟返回一个占位图
  return 'https://via.placeholder.com/300x169?text=视频预览'
}

const handleDownload = async (policy) => {
  try {
    const policyId = policy.id
    const url = `${BASE_URL}/api/v1/government/public/download/attachment/${policyId}`;
    const response = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      responseType: 'blob'
    });

    const blob = new Blob([response.data]);
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = policy.attachment.split('/').pop();
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl);
  } catch (error) {
    console.error('下载失败:', error);
    alert('下载失败，请重试');
  }
};

const fetchPolicyDetail = async (policy) => {
  try {
    const res = await request.get(BASE_URL + `/api/v1/government/public/policy/${policy.id}`)
    if (res.data && res.data.length > 0) {
      const updatedPolicy = res.data[0]
      const index = policies.value.findIndex(p => p.id === policy.id)
      if (index !== -1) {
        policies.value[index].viewCount = updatedPolicy.viewCount
      }
    }
  } catch (err) {
    console.error('获取政策失败:', err)
  }
}

const startPolling = () => {
  policies.value.forEach(policy => {
    pollIntervals.value[policy.id] = setInterval(() => {
      fetchPolicyDetail(policy)
    }, 1000)
  })
}

const stopPolling = () => {
  Object.values(pollIntervals.value).forEach(interval => clearInterval(interval))
  pollIntervals.value = {}
}

const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  const hours = d.getHours().toString().padStart(2, '0')
  const minutes = d.getMinutes().toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

const fetchPolicies = async () => {
  try {
    const res = await request.get(BASE_URL + '/api/v1/government/public/get')
    policies.value = res.data
  } catch (err) {
    console.error('获取政策失败:', err)
  }
}

const truncate = (text, length) => {
  return text && text.length > length ? text.slice(0, length) + '...' : text || ''
}

onMounted(async () => {
  await fetchPolicies()
  startPolling()
})

onUnmounted(() => {
  stopPolling()
})
</script>

<style scoped>
/* 基础样式 */
:root {
  --primary-color: #67C23A;
  --primary-hover: #5daf34;
  --secondary-color: #409EFF;
  --text-color: #333;
  --text-secondary: #666;
  --text-light: #999;
  --border-color: #e4e7ed;
  --bg-color: #f5f7fa;
  --card-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  --transition: all 0.3s ease;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
  color: var(--text-color);
  background-color: var(--bg-color);
  line-height: 1.6;
}

/* 页面容器 */
.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 30px 0;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  box-shadow: var(--card-shadow);
}

.page-title {
  font-size: 32px;
  font-weight: 600;
  color: var(--primary-color);
  margin-bottom: 15px;
  position: relative;
  display: inline-block;
  padding-bottom: 10px;
}

.page-title::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 3px;
  background: var(--primary-color);
  border-radius: 3px;
}

.page-subtitle {
  font-size: 18px;
  color: var(--text-secondary);
  font-weight: 400;
}

/* 政策列表 */
.policy-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.policy-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: var(--card-shadow);
  transition: var(--transition);
  cursor: pointer;
  overflow: hidden;
  border: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
}

.policy-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

.policy-content {
  padding: 25px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.policy-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.policy-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-color);
  flex: 1;
  line-height: 1.4;
  transition: var(--transition);
}

.policy-card:hover .policy-title {
  color: var(--primary-color);
}

.policy-tag {
  display: inline-block;
  background-color: rgba(103, 194, 58, 0.1);
  color: var(--primary-color);
  font-size: 12px;
  padding: 3px 10px;
  border-radius: 4px;
  margin-left: 10px;
  font-weight: 500;
}

.policy-tag.new-policy {
  background-color: var(--primary-color);
  color: white;
}

.policy-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
  font-size: 13px;
  color: var(--text-light);
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item i {
  margin-right: 6px;
  font-size: 14px;
  color: var(--text-secondary);
}

.policy-excerpt {
  color: var(--text-color);
  margin-bottom: 20px;
  font-size: 15px;
  line-height: 1.7;
  flex: 1;
}

.policy-video {
  margin: 20px 0;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 比例 */
  background-color: #f0f0f0;
}

.video-thumbnail img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: var(--transition);
}

.policy-card:hover .video-thumbnail img {
  transform: scale(1.05);
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: var(--primary-color);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  transition: var(--transition);
}

.policy-card:hover .video-play-icon {
  transform: translate(-50%, -50%) scale(1.1);
  background-color: white;
}

.policy-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid var(--border-color);
}

.download-btn {
  display: inline-flex;
  align-items: center;
  padding: 8px 16px;
  background-color: var(--primary-color);
  color: white;
  border-radius: 6px;
  font-size: 14px;
  border: none;
  cursor: pointer;
  transition: var(--transition);
  font-weight: 500;
}

.download-btn:hover {
  background-color: var(--primary-hover);
  transform: translateY(-2px);
}

.download-btn i {
  margin-right: 7px;
  font-size: 15px;
}

.policy-arrow {
  color: var(--secondary-color);
  font-size: 20px;
  transition: var(--transition);
}

.policy-card:hover .policy-arrow {
  transform: translateX(3px);
}

/* 响应式调整 */
@media (max-width: 768px) {
  .policy-list {
    grid-template-columns: 1fr;
  }

  .page-title {
    font-size: 28px;
  }

  .page-subtitle {
    font-size: 16px;
  }

  .policy-content {
    padding: 20px;
  }

  .policy-title {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 24px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .policy-meta {
    flex-direction: column;
    gap: 8px;
  }
}
</style>